package online.hxstar.learn.nio.bio2;

import online.hxstar.learn.util.DateUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.LocalDateTime;

/**
 * @author huxing
 * @date 2018-12-13 9:07
 * @describe 时间服务器处理类
 */
public class TimeServerHandler implements Runnable {

    private Socket socket;

    TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        PrintWriter printWriter = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            printWriter = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime;
            String body;
            while (true) {
                body = bufferedReader.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("The time server receive order :" + body);
                System.out.println("ThreadName:"+Thread.currentThread().getName());
                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? DateUtils.timeToStr(LocalDateTime.now()) : "BAD ORDER";
                printWriter.println(currentTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
                if (this.socket != null) {
                    this.socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
